package com.clkj.zhonghui.service.pay;

import com.clkj.zhonghui.dao.order.MainOrderMapper;
import com.clkj.zhonghui.dao.points.RebatePointsMapper;
import com.clkj.zhonghui.dao.points.RebateRelationsMapper;
import com.clkj.zhonghui.dao.points.RebateSettingsMapper;
import com.clkj.zhonghui.dao.stored.UserActMapper;
import com.clkj.zhonghui.dao.stored.UserStoredDetailMapper;
import com.clkj.zhonghui.dao.stored.UserStoredMapper;
import com.clkj.zhonghui.dao.user.UserMapper;
import com.clkj.zhonghui.pojo.common.*;
import com.clkj.zhonghui.pojo.order.MainOrder;
import com.clkj.zhonghui.pojo.points.RebatePoints;
import com.clkj.zhonghui.pojo.points.RebateRelations;
import com.clkj.zhonghui.pojo.stored.UserAct;
import com.clkj.zhonghui.pojo.stored.UserStored;
import com.clkj.zhonghui.pojo.stored.UserStoredDetail;
import com.clkj.zhonghui.pojo.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yawang
 * @create 2024/07/12 09:30:04
 **/
@Service
public class PayServiceImpl implements PayService{
    @Autowired
    private MainOrderMapper mainOrderMapper;
    @Autowired
    private UserStoredDetailMapper userStoredDetailMapper;
    @Autowired
    private UserStoredMapper userStoredMapper;

    @Autowired
    private UserActMapper userActMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RebateRelationsMapper rebateRelationsMapper;

    @Autowired
    private RebatePointsMapper rebatePointsMapper;

    @Autowired
    private RebateSettingsMapper rebateSettingsMapper;
    private Map map;
    @Override
    public Map<String, Object> pay(Integer userId, Integer shopId, String orderNumber, Integer parentId, String realMoney, Double rebate,
                                   Integer flag, String openId, Integer ifDown, HttpServletRequest request) {
        SortedMap<String,Object> packageParams = new TreeMap();

        orderNumber = orderNumber +"A"+((int) (Math.random() * 90) + 10);
        System.out.println(orderNumber);
        String redirect_url="https://www.ccclkj.cn:2040/pay/payOrderSuccess";
        //处理业务
        String appId="";
        String appSecret="";
        String trade_type="";
        if(flag==1){
            //微信端支付
            appId = PayApi.wxAppId;
            appSecret =PayApi.wxAppSecret;
            trade_type="JSAPI";
        }else{
            appId = PayApi.AppId;
            appSecret =PayApi.AppSecret;
            trade_type="APP";
        }


        String nonceStr = Util.getRandomIntegerByLength(32);
        String Ip = Util.getIpAddr(request);
        String totalFee = Util.getMoney(realMoney);


        String attach = userId + "@" + parentId + "@" + rebate+"@"+ifDown+"@"+shopId;
        String partner = PayApi.partner;// appid
        String partnerKey = PayApi.partnerKey;

        String body = "中汇商品购买";


        packageParams.put("appid",appId);
        packageParams.put("attach",attach);
        packageParams.put("body",body);
        packageParams.put("mch_id",partner);
        packageParams.put("nonce_str", nonceStr);
        packageParams.put("notify_url",redirect_url);
        packageParams.put("out_trade_no",orderNumber);
        packageParams.put("spbill_create_ip", Ip);
        packageParams.put("total_fee",totalFee);
        packageParams.put("trade_type",trade_type);
        if(flag==1){
            packageParams.put("openid",openId);
        }


        RequestHandler requestHandler = new RequestHandler(null,null);
        requestHandler.init(appId,appSecret ,partner,partnerKey);
        String sign = requestHandler.createSign(packageParams);
        System.out.println(sign);
        String xml = "<xml>" + "<appid>" + appId + "</appid>" + "<attach>"
                + attach + "</attach>" + "<body><![CDATA[" + body
                + "]]></body>" + "<mch_id>" + partner + "</mch_id>"
                + "<nonce_str>" + nonceStr + "</nonce_str>" + "<notify_url>"
                + redirect_url + "</notify_url>" + "<out_trade_no>"
                + orderNumber + "</out_trade_no>" +
                "<spbill_create_ip>" + Ip + "</spbill_create_ip>"
                + "<sign>" + sign + "</sign>" + "<total_fee>" + totalFee
                + "</total_fee>" + "<trade_type>" + trade_type
                + "</trade_type>" ;
                if(flag==1){
                    xml+=  "<openid>" + openId + "</openid>";
                }
                xml+= "</xml>";
        System.out.println(xml);
        String prePayId = "";
        String createdOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String result = PayUtil.httpRequest(createdOrderURL,"POST",xml);
        System.out.println(result);
        SortedMap<String,Object> finalpackage = new TreeMap();
        try {
            Map map = PayUtil.doXMLParse(result);
            String str = String.valueOf(System.currentTimeMillis()/1000);
            String returnCode = map.get("return_code").toString();
            if(returnCode.equals("SUCCESS")){
                prePayId = map.get("prepay_id").toString();

                finalpackage.put("appid",appId);
                finalpackage.put("timestamp",str);
                finalpackage.put("noncestr",nonceStr);

                if(flag==0){//app支付
                    finalpackage.put("package","Sign=WXPay");
                    finalpackage.put("partnerid",partner);
                    finalpackage.put("prepayid",prePayId);
                    String finalSign = requestHandler.createSign(finalpackage);
                    finalpackage.put("sign",finalSign);
                }else{//微信支付
                    finalpackage.put("package","prepay_id=" + prePayId);
                    finalpackage.put("signType", "MD5");
                    String finalSign = requestHandler.createSign(finalpackage);
                    finalpackage.put("paySign", finalSign);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map = new HashMap();
        map.put("finalPackage",finalpackage);

        return map;
    }

    @Override
    public void payOrderSuccess(HttpServletRequest request, HttpServletResponse response) {
        System.out.println( "回调进来了");
        String resXml = "";
        InputStream inStream;
        String attach="";
        String order_num="";
        double money=0.0;
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map m = PayUtil.parseXmlToList2(result);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            if ("SUCCESS".equals(m.get("result_code").toString())) {
                // 更新支付状态
                order_num = m.get("out_trade_no").toString().split("A")[0];
                System.out.println(order_num + "订单号是什么");
                // 获取微信生成的订单号
                String transaction_id = m.get("transaction_id").toString();
                money = Double.valueOf(m.get("total_fee").toString())/100l;

                Example example = new Example(MainOrder.class);
                Example.Criteria criteria = example.createCriteria();

                criteria.andEqualTo("orderNum",order_num);
                MainOrder mainOrder = new MainOrder();
                mainOrder.setOrderStatus(1);
                mainOrder.setTransactionId(transaction_id);
                mainOrderMapper.updateByExampleSelective(mainOrder,example);
                resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";

            } else {
                resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";

            }
            out.write(resXml.getBytes());
            out.flush();
            out.close();

            attach= m.get("attach").toString();
            String[] str = attach.split("@");
//            String attach = userId + "@" + parentId + "@" + rebate +“@”+ifDown;
            Integer userId = Integer.valueOf(str[0]);
            Integer parentId = Integer.valueOf(str[1]);
            Double rebate = Double.valueOf(str[2]);//
            Integer ifDown = Integer.valueOf(str[3]);
            Integer shopId = Integer.valueOf(str[4]);
            if(ifDown==0){
                User user = new User();
                user.setUserId(userId);
                user.setIfDown(1);
                //这里需要修改用户表
                userMapper.updateByPrimaryKeySelective(user);
            }
            if(parentId==-1){
                //鸡胚胎
                Example example = new Example(UserAct.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId",Integer.parseInt(str[0]));
                UserAct at = new UserAct();
                at.setIsFirst(1);
                userActMapper.updateByExampleSelective(at,example);
            }
            if(parentId==-2){
                //优惠券
                Example example = new Example(UserAct.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId",Integer.parseInt(str[0]));
                UserAct at = new UserAct();
                at.setIsCoupon(0);
                at.setInvaildTime(null);
                userActMapper.updateByExampleSelective(at,example);
            }
            if(parentId!=0&&rebate>0&&parentId!=userId){
                UserStoredDetail detail = new UserStoredDetail();
                detail.setDateTime(DateFormatHelper.currentTimes());
                detail.setOrderNumber(order_num);
                detail.setShareMoney(rebate);
                detail.setUserId(userId);
                detail.setShareId(parentId);
                detail.setStoredMoney(money);
                detail.setStoredFlag(1);
                userStoredDetailMapper.insertSelective(detail);
                userStoredMapper.updateParentStored(parentId,rebate,shopId);//给父级家返利金额

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map payMiniOrder(Integer userId, Integer shopId, String orderNumber, Integer parentId, Integer highestId,Integer note,String realMoney, String rebate, String rebates, String openId, HttpServletRequest request) {
        SortedMap<String,Object> packageParams = new TreeMap();

        orderNumber = orderNumber +"A"+((int) (Math.random() * 90) + 10);
        System.out.println(orderNumber);
        String redirect_url="https://www.ccclkj.cn:2040/pay/payMiniOrderSuccess";
        //处理业务
        //小程序支付
        String appId=PayApi.miniAppId;
        String appSecret=PayApi.miniAppSecret;
        String trade_type="JSAPI";
        String partner = PayApi.partner;// appid
        String partnerKey = PayApi.partnerKey;

        String nonceStr = Util.getRandomIntegerByLength(32);
        String Ip = Util.getIpAddr(request);
        String totalFee = Util.getMoney(realMoney);
        String attach = userId + "@" + parentId + "@" + highestId + "@" + rebate + "@" + rebates +"@" + note +"@" + realMoney;
        String mchId = partner;
        String body = "中汇套餐商品购买";


        packageParams.put("appid",appId);
        packageParams.put("attach",attach);
        packageParams.put("body",body);
        packageParams.put("mch_id",mchId);
        packageParams.put("nonce_str", nonceStr);
        packageParams.put("notify_url",redirect_url);
        packageParams.put("out_trade_no",orderNumber);
        packageParams.put("spbill_create_ip", Ip);
        packageParams.put("total_fee",totalFee);
        packageParams.put("trade_type",trade_type);
        packageParams.put("openid",openId);


        RequestHandler requestHandler = new RequestHandler(null,null);
        requestHandler.init(appId,appSecret ,partner,partnerKey);
        String sign = requestHandler.createSign(packageParams);
        System.out.println(sign);
        String xml = "<xml>" +
                "<appid>" + appId + "</appid>" +
                "<attach>" + attach + "</attach>" +
                "<body><![CDATA[" + body + "]]></body>" +
                "<mch_id>" + mchId + "</mch_id>" +
                "<nonce_str>" + nonceStr + "</nonce_str>" +
                "<notify_url>" + redirect_url + "</notify_url>" +
                "<out_trade_no>" + orderNumber + "</out_trade_no>" +
                "<spbill_create_ip>" + Ip + "</spbill_create_ip>" +
                "<sign>" + sign + "</sign>" +
                "<total_fee>" + totalFee + "</total_fee>" +
                "<trade_type>" + trade_type + "</trade_type>" +
                "<openid>" + openId + "</openid>"+ "</xml>";
        System.out.println(xml);
        String prePayId = "";
        String createdOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String result = PayUtil.httpRequest(createdOrderURL,"POST",xml);
        System.out.println(result);
        SortedMap<String,Object> finalpackage = new TreeMap();
        try {
            Map map = PayUtil.doXMLParse(result);
            String str = String.valueOf(System.currentTimeMillis()/1000);
            String returnCode = map.get("return_code").toString();
            if(returnCode.equals("SUCCESS")){
                prePayId = map.get("prepay_id").toString();
                finalpackage.put("appId",appId);
                finalpackage.put("timeStamp",str);
                finalpackage.put("nonceStr",nonceStr);

                finalpackage.put("package","prepay_id=" + prePayId);
                finalpackage.put("signType", "MD5");
                String finalSign = requestHandler.createSign(finalpackage);
                finalpackage.put("paySign", finalSign);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map = new HashMap();
        map.put("finalPackage",finalpackage);

        return map;
    }

    @Override
    public void payMiniOrderSuccess(HttpServletRequest request, HttpServletResponse response) {
        System.out.println( "回调进来了");
        String resXml = "";
        InputStream inStream;
        String attach="";
        String order_num="";
        String date = DateFormatHelper.currentTimes();
        double money=0.0;
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map m = PayUtil.parseXmlToList2(result);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            if ("SUCCESS".equals(m.get("result_code").toString())) {
                // 更新支付状态
                order_num = m.get("out_trade_no").toString().split("A")[0];
                System.out.println(order_num + "订单号是什么");
                // 获取微信生成的订单号
                String transaction_id = m.get("transaction_id").toString();
                money = Double.valueOf(m.get("total_fee").toString())/100l;

                Example example = new Example(MainOrder.class);
                Example.Criteria criteria = example.createCriteria();

                criteria.andEqualTo("orderNumber",order_num);
                MainOrder mainOrder = new MainOrder();
                mainOrder.setOrderStatus(1);
                mainOrder.setTransactionId(transaction_id);
                mainOrderMapper.updateByExampleSelective(mainOrder,example);
                resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";

            } else {
                resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";

            }
            out.write(resXml.getBytes());
            out.flush();
            out.close();

            attach= m.get("attach").toString();
            String[] str = attach.split("@");
//            String attach =userId + "@" + parentId + "@" + highestId + "@" + rebate + "@" + rebates +"@" + note +"@" + realMoney;
            Integer userId = Integer.valueOf(str[0]);
            Integer parentId = Integer.valueOf(str[1]);
            Integer highestId = Integer.valueOf(str[2]);
            Double rebate = Double.valueOf(str[3]);
            Double rebates = Double.valueOf(str[4]);
            Integer note = Integer.valueOf(str[5]);
            Double realMoney = Double.valueOf(str[6]);

            Example example = new Example(RebateRelations.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", parentId);
            criteria.andEqualTo("note", 1);
            RebateRelations parentNode = rebateRelationsMapper.listRelations(parentId);

            example = new Example(RebateRelations.class);
            criteria = example.createCriteria();
            criteria.andEqualTo("userId", highestId);
            criteria.andEqualTo("note", 1);
            RebateRelations highestNode = rebateRelationsMapper.listRelations(highestId);

            //为上级返积分
            if(parentId != 0 && rebate > 0 && parentId !=userId && parentNode!=null){
                RebatePoints rebatePoints = new RebatePoints();
                rebatePoints.setUserId(parentId);
                rebatePoints.setSource(userId);
                rebatePoints.setPoints(rebate);
                rebatePoints.setOrderNum(order_num);
                rebatePoints.setEarnedDate(date);
                Calendar calendar = Calendar.getInstance();
                try {
                    calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                calendar.add(Calendar.DAY_OF_MONTH, 60);
                String expiryDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
                rebatePoints.setExpiryDate(expiryDate);
                rebatePoints.setSurplusPoints(rebate);
                rebatePoints.setPointType(1);
                rebatePointsMapper.insertSelective(rebatePoints);
            }

            //为上上级返积分
            if(highestId != 0 && rebates > 0 && highestId != userId && highestNode!=null){
                RebatePoints rebatePoints = new RebatePoints();
                rebatePoints.setUserId(highestId);
                rebatePoints.setSource(userId);
                rebatePoints.setPoints(rebates);
                rebatePoints.setOrderNum(order_num);
                rebatePoints.setEarnedDate(date);
                Calendar calendar = Calendar.getInstance();
                try {
                    calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                calendar.add(Calendar.DAY_OF_MONTH, 60);
                String expiryDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
                rebatePoints.setExpiryDate(expiryDate);
                rebatePoints.setSurplusPoints(rebates);
                rebatePoints.setPointType(1);
                rebatePointsMapper.insertSelective(rebatePoints);
            }
            example = new Example(RebateRelations.class);
            criteria = example.createCriteria();
            criteria.andEqualTo("userId",userId);
            RebateRelations rebateRelations = rebateRelationsMapper.selectOneByExample(example);
            //如果当前用户没有关系记录，就新增关系记录
            if(rebateRelations == null){
                RebateRelations rebateRelations1 =new RebateRelations();
                rebateRelations1.setUserId(userId);
                if(parentId!=0){
                    rebateRelations1.setReferrerId(parentId);
                }else {
                    rebateRelations1.setReferrerId(0);
                }
                rebateRelations1.setNote(1);
                rebateRelationsMapper.insertSelective(rebateRelations1);
            }else {
                if(note != 1){
                    rebateRelationsMapper.updatePointsNode(userId);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map payMiniProductOrder(Integer userId, Integer shopId, String orderNumber, String realMoney, Double usedYh, String openId, HttpServletRequest request) {
        SortedMap<String,Object> packageParams = new TreeMap();

        orderNumber = orderNumber +"A"+((int) (Math.random() * 90) + 10);
        System.out.println(orderNumber);
        String redirect_url="https://www.ccclkj.cn:2040/pay/payMiniProductOrderSuccess";
        //处理业务
        //小程序端支付
        String appId=PayApi.miniAppId;
        String appSecret=PayApi.miniAppSecret;
        String trade_type="JSAPI";
        String partner = PayApi.partner;// appid
        String partnerKey = PayApi.partnerKey;

        String nonceStr = Util.getRandomIntegerByLength(32);
        String Ip = Util.getIpAddr(request);
        String totalFee = Util.getMoney(realMoney);


        String attach = userId + "@" + realMoney + "@" + usedYh + "@" + shopId;
        String mchId = partner;
        String body = "中汇普通商品购买";


        packageParams.put("appid",appId);
        packageParams.put("attach",attach);
        packageParams.put("body",body);
        packageParams.put("mch_id",mchId);
        packageParams.put("nonce_str", nonceStr);
        packageParams.put("notify_url",redirect_url);
        packageParams.put("out_trade_no",orderNumber);
        packageParams.put("spbill_create_ip", Ip);
        packageParams.put("total_fee",totalFee);
        packageParams.put("trade_type",trade_type);
        packageParams.put("openid",openId);
        RequestHandler requestHandler = new RequestHandler(null,null);
        requestHandler.init(appId,appSecret ,partner,partnerKey);
        String sign = requestHandler.createSign(packageParams);
        System.out.println(sign);
        String xml = "<xml>" +
                "<appid>" + appId + "</appid>" +
                "<attach>" + attach + "</attach>" +
                "<body><![CDATA[" + body + "]]></body>" +
                "<mch_id>" + mchId + "</mch_id>" +
                "<nonce_str>" + nonceStr + "</nonce_str>" +
                "<notify_url>" + redirect_url + "</notify_url>" +
                "<out_trade_no>" + orderNumber + "</out_trade_no>" +
                "<spbill_create_ip>" + Ip + "</spbill_create_ip>" +
                "<sign>" + sign + "</sign>" +
                "<total_fee>" + totalFee + "</total_fee>" +
                "<trade_type>" + trade_type + "</trade_type>"+
                "<openid>" + openId + "</openid>"+ "</xml>";
        System.out.println(xml);
        String prePayId = "";
        String createdOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String result = PayUtil.httpRequest(createdOrderURL,"POST",xml);
        System.out.println(result);
        SortedMap<String,Object> finalpackage = new TreeMap();
        try {
            Map map = PayUtil.doXMLParse(result);
            String str = String.valueOf(System.currentTimeMillis()/1000);
            String returnCode = map.get("return_code").toString();
            if(returnCode.equals("SUCCESS")){
                prePayId = map.get("prepay_id").toString();
                finalpackage.put("appId",appId);
                finalpackage.put("timeStamp",str);
                finalpackage.put("nonceStr",nonceStr);
                finalpackage.put("package","prepay_id=" + prePayId);
                finalpackage.put("signType", "MD5");
                String finalSign = requestHandler.createSign(finalpackage);
                finalpackage.put("paySign", finalSign);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map = new HashMap();
        map.put("finalPackage",finalpackage);

        return map;
    }

    @Override
    public void payMiniProductOrderSuccess(HttpServletRequest request, HttpServletResponse response) {
        System.out.println( "回调进来了");
        String resXml = "";
        InputStream inStream;
        String attach="";
        String order_num="";
        double money=0.0;
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map m = PayUtil.parseXmlToList2(result);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            if ("SUCCESS".equals(m.get("result_code").toString())) {
                // 更新支付状态
                order_num = m.get("out_trade_no").toString().split("A")[0];
                System.out.println(order_num + "订单号是什么");
                // 获取微信生成的订单号
                String transaction_id = m.get("transaction_id").toString();
                Example example = new Example(MainOrder.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("orderNumber",order_num);
                MainOrder mainOrder = new MainOrder();
                mainOrder.setOrderStatus(1);
                mainOrder.setTransactionId(transaction_id);
                mainOrderMapper.updateByExampleSelective(mainOrder,example);
                resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";

            } else {
                resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";

            }
            out.write(resXml.getBytes());
            out.flush();
            out.close();

            attach= m.get("attach").toString();
            String[] str = attach.split("@");
//          String attach = userId + "@" + realMoney + "@" + usedYh + "@" + shopId;
            Integer userId = Integer.valueOf(str[0]);
            Double realMoney = Double.valueOf(str[1]);//现金
            Double usedYh = Double.valueOf(str[2]);//积分
            Double usedYh1 = Double.valueOf(str[2]);//积分
            Integer shopId = Integer.valueOf(str[3]);

            if (usedYh != 0) {
                Example example = new Example(RebatePoints.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId", userId);
                criteria.andIn("pointType", Arrays.asList(1, 3));
                Date currentDate = new Date();
                criteria.andGreaterThan("expiryDate", currentDate);
                example.orderBy("expiryDate").asc();
                List<RebatePoints> rebatePointsList = rebatePointsMapper.selectByExample(example);
                for (RebatePoints rebatePoint : rebatePointsList) {
                    if (usedYh >= rebatePoint.getSurplusPoints()) {
                        usedYh -= rebatePoint.getSurplusPoints(); // 更新可用积分数量
                        rebatePoint.setSurplusPoints(0.0);
                        rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                    } else if (usedYh > 0 && rebatePoint.getSurplusPoints() > 0) {
                        double originalSurplusPoints = rebatePoint.getSurplusPoints();
                        rebatePoint.setSurplusPoints(originalSurplusPoints - usedYh); // 更新剩余积分券数量
                        usedYh = 0.0;
                        rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                        break; //没有更多的积分可以扣除了
                    }
                }
                RebatePoints rebatePoints = new RebatePoints();
                rebatePoints.setUserId(userId);
                rebatePoints.setPoints(usedYh1);
                rebatePoints.setOrderNum(order_num);
                rebatePoints.setEarnedDate(DateFormatHelper.currentTimes());
                rebatePoints.setPointType(0);
                rebatePointsMapper.insertSelective(rebatePoints);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
